package com.jeomo.mem.starter.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.entity.Merchant;
import com.jeomo.masterdata.starter.mapper.GoodsMapper;
import com.jeomo.masterdata.starter.mapper.MerchantMapper;
import com.jeomo.mem.starter.dto.MemberPointActivityDto;
import com.jeomo.mem.starter.entity.MemberPointsActivityExe;
import com.jeomo.mem.starter.entity.MemberPointsActivityRule;
import com.jeomo.mem.starter.entity.MemberPointsActivityRuleList;
import com.jeomo.mem.starter.mapper.MemberPointsActivityListMapper;
import com.jeomo.mem.starter.mapper.MemberPointsActivityRuleMapper;
import com.jeomo.mem.starter.service.IMemPointsActivityRuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 会员积分活动
 * @author:Jackpot
 * @create 2020-09-29 16:27
 * @description:
 */
@Service
@Transactional
public class MemPointsActivityRuleServiceImpl extends BaseServiceImpl<MemberPointsActivityListMapper, MemberPointsActivityRuleList>
        implements IMemPointsActivityRuleService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String RULE_CODE = "rule_code";

    @Resource
    private MemberPointsActivityRuleMapper memberPointsActivityRuleMapper;
    @Resource
    private MemberPointsActivityListMapper memberPointsActivityListMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private MerchantMapper merchantMapper;

    @Override
    public int saveRule(MemberPointsActivityRule memberPointsActivityRule, List<MemberPointsActivityRuleList> memberPointsActivityRuleLists) {
        int result = 0;
        String code = memberPointsActivityRule.getCode();

        if (StringUtils.isNotEmpty(code)){
            MemberPointsActivityRule memberPointsActivityRule1 = memberPointsActivityRuleMapper.selectById(code);
            if (memberPointsActivityRule1 !=null){
                //修改规则
                result = saveRule(memberPointsActivityRule,memberPointsActivityRuleLists,false);
            }else {
                //数据已被删除
                return -2;
            }
        }else{
            //新增规则
            result = saveRule(memberPointsActivityRule,memberPointsActivityRuleLists,true);
        }
        return result;
    }

    @Override
    public int saveRule(MemberPointsActivityRule memberPointsActivityRule, List<MemberPointsActivityRuleList> memberPointsActivityRuleLists, boolean addOrUpdate) {

        memberPointsActivityRule.setUseLevels(StringUtils.arrayToStr(memberPointsActivityRule.getLevelCodes()));
        int masterResult = 0;
        String code = memberPointsActivityRule.getCode();
        if(addOrUpdate==true){
            //新增规则
            masterResult = memberPointsActivityRuleMapper.insert(memberPointsActivityRule);
            code = memberPointsActivityRule.getCode();
        }else{
            //修改规则: 修改主表,删除子表原数据,新增子表数据
            masterResult = memberPointsActivityRuleMapper.updateById(memberPointsActivityRule);
            if(masterResult < 1) return -1;
            int delList = deleteRuleDetail(code);
        }
        int detailResult = insertRuleDetail(memberPointsActivityRuleLists, code);
        return masterResult+detailResult;
    }


    @Override
    public int insertRuleDetail(List<MemberPointsActivityRuleList> memberPointsRuleList, String ruleCode) {
        Iterator<MemberPointsActivityRuleList> iterator = memberPointsRuleList.iterator();
        while (iterator.hasNext()){
            iterator.next().setRuleCode(ruleCode);
        }
        return saveBatch(memberPointsRuleList) == true?1:0;
    }

    @Override
    public int deleteRule(String ruleCode) {
        int delList = deleteRuleDetail(ruleCode);
        int delMaster = memberPointsActivityRuleMapper.deleteById(ruleCode);
        return delList+delMaster;
    }

    @Override
    public int deleteRuleDetail(String ruleCode) {
        QueryWrapper<MemberPointsActivityRuleList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(RULE_CODE,ruleCode);
        return memberPointsActivityListMapper.delete(queryWrapper);
    }

    @Override
    public MemberPointActivityDto getMemberPointRule(String ruleCode) {

        MemberPointsActivityRule memberRule = memberPointsActivityRuleMapper.selectById(ruleCode);
        QueryWrapper<MemberPointsActivityRuleList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(RULE_CODE,ruleCode);
        List<MemberPointsActivityRuleList> memberRuleList = memberPointsActivityListMapper.selectList(queryWrapper);
        MemberPointActivityDto memberActivityDto = new MemberPointActivityDto();
        memberActivityDto.setMemberPointsActivityRule(memberRule);
        memberActivityDto.setMemberPointsActivityLists(memberRuleList);
        return memberActivityDto;
    }


    @Override
    public Map<String,MemberPointsActivityExe> getActivities(String levelCode, String goodsCode, double amount,Date handleDate) {
        Goods goods = goodsMapper.selectById(goodsCode);
        if (goods == null) return null;
        String merchantCode = goods.getMerchantCode();
        //根据会员等级,时间,消费金额找出匹配的活动规则明细
        List<MemberPointsActivityExe> activityRules = memberPointsActivityRuleMapper.getAllActivitiesByCond(handleDate, levelCode, amount);
        List<MemberPointsActivityExe> activityRulesExclude = new ArrayList<>();
        //把白名单和黑名单分开
        Iterator<MemberPointsActivityExe> iterator = activityRules.iterator();
        while (iterator.hasNext()){
            MemberPointsActivityExe activity = iterator.next();
            if (activity.getPermit()==false){
                activityRulesExclude.add(activity);
                iterator.remove();
            }
        }
        //根据黑名单确定排除的积分活动
        HashMap<String, MemberPointsActivityExe> activityExcludeMap = new HashMap<>(8);
        for (MemberPointsActivityExe activityExe: activityRulesExclude){
            String bsCode = activityExe.getBsCode();
            //目前匹配规则的排除名单里只有商品和商户两种类型
            if(bsCode.equals(goodsCode) || bsCode.equals(merchantCode)){
                activityExcludeMap.put(activityExe.getRuleCode(),activityExe);
            }
        }
        // 去除排除的积分活动
        HashMap<String, MemberPointsActivityExe> activityMap = new HashMap<>();
        for (MemberPointsActivityExe activityExe: activityRules){
            if(activityExcludeMap.get(activityExe.getRuleCode())==null){
                activityMap.put(activityExe.getRuleCode(),activityExe);
            }
        }
        //
        Collection<MemberPointsActivityExe> activities = activityMap.values();
        Iterator<MemberPointsActivityExe> iterator1 = activities.iterator();
        while (iterator1.hasNext()){
            MemberPointsActivityExe activity = iterator1.next();
            String bsCode = activity.getBsCode();
            //商品对应的积分活动规则
            if (bsCode.equals(goodsCode)) continue;
            //查询品类的规则
            if (bsCode.equals(goods.getGoodsTypeCode())) continue;
            //查询商户的规则
            if (bsCode.equals(merchantCode)) continue;
            //查询业态的规则
            Merchant merchant = merchantMapper.selectById(merchantCode);
            if (merchant != null && bsCode.equals(merchant.getTobCode())) continue;
            //否则不符合规则,移除
            iterator1.remove();
        }
        return activityMap;
    }
}
